﻿using System;
using CxExtension;
using JetBrains.Annotations;

namespace UnityEngine
{
	public static class GameObjectExt
	{
		/// <summary>
		/// foreach components list use pool list
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="self"></param>
		/// <param name="action"></param>
		/// <param name="includeInactive"></param>
		public static void GetComponentsInChildrenForeach<T>([NotNull] this GameObject self, [NotNull] Action<T> action, bool includeInactive = false)
			//where T : Component
		{
			if (self == null) throw new ArgumentNullException(nameof(self));
			if (action == null) throw new ArgumentNullException(nameof(action));

			var list = ListPool<T>.Get();
			self.GetComponentsInChildren(includeInactive, list);
			foreach (var it in list)
			{
				action(it);
			}
			ListPool<T>.Recycle(list);
		}
		/// <summary>
		/// foreach components list use pool list
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="self"></param>
		/// <param name="action"></param>
		/// <param name="includeInactive"></param>
		public static void GetComponentsForeach<T>([NotNull] this GameObject self, [NotNull] Action<T> action)
			//where T : Component
		{
			if (self == null) throw new ArgumentNullException(nameof(self));
			if (action == null) throw new ArgumentNullException(nameof(action));

			var list = ListPool<T>.Get();
			self.GetComponents(list);
			foreach (var it in list)
			{
				action(it);
			}
			ListPool<T>.Recycle(list);
		}
		/// <summary>
		/// foreach components list use pool list
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="self"></param>
		/// <param name="action"></param>
		/// <param name="includeInactive"></param>
		public static void GetComponentsInParentForeach<T>([NotNull] this GameObject self, [NotNull] Action<T> action, bool includeInactive = false)
			//where T : Component
		{
			if (self == null) throw new ArgumentNullException(nameof(self));
			if (action == null) throw new ArgumentNullException(nameof(action));

			var list = ListPool<T>.Get();
			self.GetComponentsInParent(includeInactive,list);
			foreach (var it in list)
			{
				action(it);
			}
			ListPool<T>.Recycle(list);
		}

	}
}